<template><!--作业-->
    <div style="height: 100%;">
        <navbar :title="$t('mod_ASS')" :backCallback="back">
            <template #right>
                <span v-if="!uploadingFile && !isTimeOut() && (!upfiles[assList] || !upfiles[assList].name)" class="write-btn-right font-size15 head-right" style="color: #ccc;">{{ $t("button_submit") }}</span><!--提交-->
                <span v-if="!uploadingFile && !isTimeOut() && upfiles[assList] && upfiles[assList].name" class="write-btn-right font-size15 head-right cur" v-debounce="() => submit()">{{ $t("button_submit") }}</span><!--提交-->
            </template>
        </navbar>
        <div class="content-noBottom" style="overflow-x: auto">
            <div>
                <div class="ass-nav">
                    <div class="ass-nav-title" v-if="title">{{title}}</div>
                    <div v-if="fileSuffix === '.MP4' || fileSuffix === '.M3U8'">
                        <xg-player :videoConfig="videoConfig"></xg-player>
                    </div>
                    <div v-else-if="videoConfig.videoUrl" style="text-align: right;color: #999999">
                        <span>{{ $t("download_tip_2") }}</span>
                        <input id="resourcesPath" style="position: absolute;left: -1px;top: -1px;z-index: -10">
                    </div>
                    <div class="font-size11" style="margin-bottom: 20px;">
                        <span v-if="desc">{{ desc }} </span>
                        <div v-if="isTimeOut()">
                            <span class="warning-red-tan"></span>
                            <span class="colorfd3">{{ $t("mod_tips_8") }}</span><!--作业提交截止时间已过-->
                        </div>
                    </div>
                    <div>
                        <div style="position: relative" class="color999" v-if="ass.source && ass.source[0].type == 'null'">
                            <span v-if="expand == false">{{ass.instruction[0].text}}</span>
                            <span v-if="expand == true">{{expandText(ass.instruction[0].text)}}...</span>
                            <div class="expand" v-if="expand == true" @click="expand = false">
                                <span><!--展开-->
                                    {{ $t("button_expand") }} <img src="./images/expand.png" alt="">
                                </span>
                            </div>
                        </div>
                        <div v-if="ass.source && ass.source[0].type != 'null'" class="other-upFile-style" @click="showFile">
                            <div>
                                <i class="link-document"></i>
                            </div>
                            <div>
                                <span>{{text | omit(text)}}</span>
                                <span v-if="ass.source[0].type != 'URL'">{{ parseInt(fileSize / 1024) }}kb</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-if="!isTimeOut()" style="padding: 15px 0;background: #ffffff;margin-top: 12px;">
                <div class="paddingLR15">
                   <div class="font-size15"><!--作业提交-->
                       {{ $t("mod_tips_9") }}
                   </div>
                    <span class="font-size11 color999" style="margin: 10px 0 40px 0;display: block;">{{ $t("mod_tips_10") }}</span>
                </div>
                <div class="paddingLR15" v-for="(item, index) in assListArr" :key="index">
                    <p class="work-title">
                        <span>{{ $t("mod_ASS") }} {{ item > 9 ? item : ('0' + Number(item)) }}</span>
                        <span v-if="index > 0" class="del-btn" @click="deleteWork(item, index, assNames[index])"><i class="iconfont icon-huishouzhan" style="font-size:18px"></i></span>
                    </p>
                    <div>
                        <input v-validate="'required'" hidden :id="item" type="file" @change="upFile($event, item)" name="assFile" accept=".doc,.docx,.xls,.xlsx,.pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
                        <label :for="item">
                            <div class="upfile" :class="{'color999' : !assNames[index]}">{{ assNames[index] ? assNames[index] : $t("mod_ass_add_file") }}</div>{{$t("mod_ass_add_file")}}
                        </label>
                    </div>
                    <textarea contenteditable="true" @input="comment($event, item)" class="assDesc" :placeholder="$t('mod_ass_add_file_describe')">
                    </textarea><!--输入对作业的描述...-->
                    <div v-if="numState">
                        <i  class="warning-red-tan"></i>
                        <span class="colorfd3">{{ $t('exceeded_word_range_tips', {'value': '400'}) }}</span><!--已超出400中文范围-->
                    </div>
                </div>
                <!--新增另一个作业文件-->
                <div class="addFile" v-if="!upfiles[assList] || !upfiles[assList].name">
                    {{ $t("mod_ass_add_other_file") + assList}}
                </div>
                <div class="addFile cur" @click="addFile" v-if="upfiles[assList] && upfiles[assList].name">
                    {{ $t("mod_ass_add_other_file") }}
                </div>
            </div>
        </div>
        <!--tip-->
        <van-dialog
            v-model="assTips"
            show-cancel-button
            :title="$t('confirm_exit_1')"
            :message="$t('confirm_exit_content_2')"
            :confirmButtonText="$t('sure')"
            :cancelButtonText="$t('cancel')"
            @confirm="$router.go(-1)"
            >
        </van-dialog>
        <van-dialog
            v-model="assSubmitTips"
            show-cancel-button
            :title="$t('confirm_exit_2')"
            :message="$t('confirm_exit_content_3')"
            :confirmButtonText="$t('sure')"
            :cancelButtonText="$t('cancel')"
            @confirm="sureSubmit()"
            >
        </van-dialog>
        <!--文档预览-->
        <div class="preview" v-if="showPreview">
            <navbar :title="$t('preview')"></navbar>
            <div class="content-noBottom">
                <iframe v-if="file" :src="previewUrl" style="height: 100%;" width="100%"  scrolling="yes" frameborder="0"/>
                <img :src="previewUrl" v-if="img" alt="">
                <video v-if="video" ref="video" :src="previewUrl" :style="'width:'+fullWidth+'px;'" controls controlslist="nodownload"></video>
            </div>
        </div>
        <!--loding-->
        <div class="saving-box" v-if="uploadingShowBox">
            <p>
                <van-loading type="spinner" size="24" />
            </p>
            <p>{{ $t("submitting") }}</p><!--提交中...-->
        </div>
      <div class="saving-box" v-if="uploadingFile">
        <p>
            <van-loading type="spinner" size="24" />
        </p>
        <p>{{ $t("uploading") }}</p><!--上传中...-->
      </div>
    </div>
</template>

<script>
import xgPlayer from '@/components/player/xgplayer';
import {Dialog, Toast, Loading} from 'vant';
export default {
    name: 'AssWork',
    components: {xgPlayer, Toast, Loading},
    data() {
        return {
            dataType: '',
            assSrc: '',
            ass: {},
            upfiles: {},
            assList: 1,
            assListArr: [1], // 作业数组
            fileDetailStr: '',
            assNames: [],
            assTips: false,
            assSubmitTips: false,
            showPreview: false, //文档预览
            text: '', //作业文档名字
            fileSize: 0, //文件大小
            uploadingShowBox: false,
            expand: false,
            file: false,
            img: false,
            video: false,
            dueTime: '', //截止时间
            fullWidth: document.documentElement.clientWidth,
            uploadingFile: false,
            desc: '', //描述
            title: '', //标题
            fileSuffix: '',
            sourceIsZip: false,
            numState: false,
            videoConfig: {
                videoUrl: '', // 播放地址
                lastPlayTime: '' // 上次播放时间
            }
        };
    },
    destroyed() {
        this.onlineCalculation('ONLINE_LEARN_DEC');
    },
    mounted() {
        this.onlineCalculation('ONLINE_LEARN_INC');
    },
    methods: {
        onlineCalculation(type) {
            this.$axios({
                method: 'GET',
                url: `/app/api/data/kanban/online/${type}/calculate`
            }).then(res => {
                console.log(res);
            });
        },
        copyFileUrl(path) {
            // let ele = document.getElementById('resourcesPath');
            // ele.value = path;
            // ele.select();
            // document.execCommand('copy');
            Dialog.alert({
                confirmButtonColor: '#00aeef',
                message: this.$t('download_tip_1')
            });
        },
        isDoc(fileExt) {
            if (!fileExt) {
                return false;
            }
            fileExt = fileExt.substring(0, 3).toLowerCase();
            if (fileExt === 'doc' || fileExt === 'xls' || fileExt === 'ppt' || fileExt === 'pdf') {
                return true;
            }
            return false;
        },
        upFile(event, index) {
            console.log(1);
            if (event && event.target.files[0]) {
                this.uploadingFile = true;
                this.upfiles[index] = {...this.upfiles[index], name: event.target.files[0].name, assFile: event.target.files[0]}; //name 文件名称  assFile：文件类型
                this.$set(this.assNames, index - 1, event.target.files[0].name);
                let param = new FormData();
                param.append('file', event.target.files[0]);
                this.$axios({
                    method: 'POST',
                    url: `/app/api/file`,
                    headers: {'Content-Type': 'multipart/form-data'},
                    data: param
                }).then(res => {
                    this.upfiles[index].url = res.data.url;
                    this.uploadingFile = false;
                });
            }
        },
        comment(e, index) {
            let num = 0;
            for (let i = 0; i < e.target.value.length; i++) {
                if (e.target.value.charCodeAt(i) > 127 || e.target.value.charCodeAt(i) === 94) {
                    num += 2;
                } else {
                    num += 1;
                }
            }
            if (num > 800) {
                this.numState = true;
            } else {
                this.numState = false;
            }
            this.upfiles[index] = {...this.upfiles[index], ...{'comment': e.target.value}};
        },
        submit() {
            if (this.numState === false) {
                this.assSubmitTips = true;
            } else {
                return false;
            }
        },
        sureSubmit() {
            //提交文件
            let fileList = [];
            this.uploadingShowBox = true;
            for (let item in this.upfiles) {
                let file = this.upfiles[item].assFile;
                //取出 后缀名
                let str = file.name;
                let index = str.lastIndexOf('.');
                str = str.substring(index, str.length);
                const obj = {
                    fileDesc: this.upfiles[item].comment,
                    fileName: file.name,
                    fileUrl: this.upfiles[item].url
                };
                fileList.push(obj);
            }
            const req = {
                fileList: fileList,
                itmId: this.$route.params.itmId,
                modId: this.$route.params.modId,
                tkhId: this.$route.params.tkhId
            };
            this.$axios({
                method: 'POST',
                url: `/app/api/trainee/course/module/ass`,
                data: req
            }).then(res => {
                this.uploadingShowBox = false;
                Toast(this.$t('successfully_submitted'));
                setTimeout(() => {
                    this.$router.go(-1);
                }, 2000);
            });
        },
        addFile() {
            if (this.upfiles[this.assList]) {
                this.assList += 1;
                this.assListArr.push(this.assList);
            };
        },
        back() {
            if (JSON.stringify(this.upfiles) === '{}') {
                this.$router.go(-1);
            } else {
                this.assTips = true;
            }
        },
        showFile() {
            this.showPreview = true;
        },
        isTimeOut() { //当前时间时候超过提交截止时间
            let nowTime = new Date();
            if (this.ass.due_datetime && this.ass.due_datetime !== 'null' && nowTime > this.conversionTime(this.ass.due_datetime)) {
                return true;
            } else {
                return false;
            }
        },
        expandText(text) {
            return text.slice(0, 180);
        },
        /**
         * 删除新增加的作业
         * */
        deleteWork(item, index, name) {
            Dialog.confirm({
                title: this.$t('delete_tip_1'),
                confirmButtonColor: '#00aeef',
                message: `${this.$t('delete_tip_2')}${this.$t('mod_ASS')}${item > 9 ? item : ('0' + item)}`
            }).then(() => {
                this.assListArr.splice(index, 1); // 删除数组列表中
                this.assListArr.forEach((v, i) => { // 若从中删除,则后面值依次递减
                    if (v > item) {
                        this.assListArr[i] = v - 1;
                    }
                });
                this.assList = this.assListArr.length;
                const upfiles = this.upfiles;
                delete upfiles[item]; // 删除文件中的对应的文件数据
                for (let key in upfiles) { // 若从中删除，则存放文件的key依次递减
                    if (key > item) {
                        upfiles[key - 1] = upfiles[key];
                        delete upfiles[key];
                    }
                }
                this.upfiles = upfiles;
                if (this.assNames.length > 2) {
                    this.assNames.splice(this.assNames.indexOf(name), 1); // 删除对应的文件名称
                }
            });
        }
    },
    filters: {
        omit(val, type) {
            if (val) {
                let nameString = val.substr(0, val.lastIndexOf('.'));
                let type = val.substr(val.lastIndexOf('.'));
                if (nameString.length > 25) {
                    nameString = `${nameString.substr(0, 14)}...${nameString.substr(-10)}`;
                }
                return `${nameString}${type}`;
            } else {
                return val;
            }
        }
    },
    created() {
        //获取详情
        this.$axios({
            method: 'GET',
            url: `/app/api/trainee/course/module/detail`,
            params: {
                itmId: this.$route.params.itmId,
                modId: this.$route.params.modId
            }
        }).then(res => {
            this.desc = res.data.instruct;
            this.title = res.data.relationVO.rcrTitle;
            this.sourceIsZip = res.data.sourceIsZip;
            if (res.data.sourceUrl) {
                this.videoConfig.videoUrl = res.data.sourceUrl ? (this.appUrl + res.data.sourceUrl) : '';
                this.fileSuffix = res.data.sourceUrl.substring(res.data.sourceUrl.lastIndexOf('.')).toUpperCase();
            }
        });
    }
};
</script>

<style scoped lang="less">
    .work-title{
        display: flex;
        justify-content: space-between;
        .del-btn{
            display: inline-block;
            width: 40px;
            text-align: right;
        }
    }
    .ass-nav{
        padding: 25px 15px;
        background: #ffffff;
        .ass-nav-title{
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
    }
    [contenteditable]:focus{outline: none;}
    .upfile{
        display: flex;
        border-bottom: 1px solid #dddddd;
        padding: 10px 0;
        align-items: center;
        font-size: 16px;
        &:before{
            content: '';
            display: inline-block;
            width: 28px;
            height: 22px;
            background: url(./images/course-icon.png) no-repeat 0 -185px;
            background-size: 20px;
        }
    }
    .assDesc {
        padding: 15px 0;
        height: 100px;
        font-size: 16px;
        width: 100%;
        border: none;
        &:empty:before {
            content: attr(placeholder);
            color: #999999;
        }
    }
    .addFile{
        height: 60px;
        display: flex;
        justify-content: center;
        padding-top: 20px;
        margin-bottom: 5px;
        font-size: 14px;
        color: #999999;
        background: #fafafa;
        box-sizing: border-box;
        &.cur{
            color: #1a1a1a;
        }
        &:before{
            content: '';
            display: block;
            width: 22px;
            height: 22px;
            background: url(./images/course-icon.png) no-repeat 0 -215px;
            background-size: 20px;
            margin-right: 10px;
            margin-top: -1px;
        }
    }
    .preview{
        position: absolute;
        top: 0;
        width: 100%;
        height: 100%;
        background: #ffffff;
    }
    .expand{
        width: 100%;
        text-align: center;
        color: #1a1a1a;
        margin-top: 10px;
    }
</style>
